"""
检索已记录的人物信息
"""
from typing import Dict, Any
from core.utils.bm25 import bm25
from models import Document

def search_characters(novel_characters: Dict, character_profile: Any):
    """ 检索已记录的人物 """
    if len(novel_characters) == 0:
        return []
    if not isinstance(character_profile, list):
        return []
    if len(character_profile) == 0:
        return []

    documents = []
    archived_characters = []
    for name, character in novel_characters.items():
        description = character.get("基本信息", None)
        if description is None:
            continue
        short_info = {
            "名称": name,
            "基本信息": description
        }
        documents.append(Document(id=name, content=str(short_info)))

    bm25.from_documents(documents)
    queries = [str(item) for item in character_profile]
    found_docs = bm25.query(queries, topn=2)
    for doc in found_docs:
        archived_characters.append(novel_characters[doc.id])
    return archived_characters